﻿package com.sgcc.nfc.lock.presentation.users

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.google.android.material.snackbar.Snackbar
import com.sgcc.nfc.lock.R
import com.sgcc.nfc.lock.databinding.FragmentUserFormBinding
import com.sgcc.nfc.lock.domain.model.RoleType
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class UserFormFragment : Fragment() {

    private var _binding: FragmentUserFormBinding? = null
    private val binding get() = _binding!!
    private val viewModel: UserFormViewModel by viewModels()

    private lateinit var regionAdapter: ArrayAdapter<String>
    private lateinit var roleAdapter: ArrayAdapter<String>
    private var regionItems: List<UserFormViewModel.SelectableRegionItem> = emptyList()
    private var roleItems: List<RoleType> = emptyList()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentUserFormBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupForm()
        observeViewModel()
    }

    private fun setupForm() {
        binding.usernameInput.setText(viewModel.username.value)
        binding.realNameInput.setText(viewModel.realName.value)
        binding.phoneInput.setText(viewModel.phone.value)

        binding.passwordLayout.isVisible = viewModel.userId == null

        regionAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, mutableListOf())
        binding.regionDropdown.setAdapter(regionAdapter)
        binding.regionDropdown.setOnItemClickListener { _, _, position, _ ->
            regionItems.getOrNull(position)?.let { viewModel.onRegionSelected(it) }
            binding.regionLayout.error = null
        }

        roleAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, mutableListOf())
        binding.roleDropdown.setAdapter(roleAdapter)
        binding.roleDropdown.setOnItemClickListener { _, _, position, _ ->
            roleItems.getOrNull(position)?.let { viewModel.onRoleSelected(it) }
            binding.roleLayout.error = null
        }

        binding.submitButton.setOnClickListener {
            binding.usernameLayout.error = null
            binding.realNameLayout.error = null
            binding.regionLayout.error = null
            binding.roleLayout.error = null

            viewModel.username.value = binding.usernameInput.text?.toString()
            viewModel.realName.value = binding.realNameInput.text?.toString()
            viewModel.phone.value = binding.phoneInput.text?.toString()
            viewModel.password.value = binding.passwordInput.text?.toString()
            viewModel.submit()
        }
    }

    private fun observeViewModel() {
        viewModel.regionItems.observe(viewLifecycleOwner) { items ->
            regionItems = items
            regionAdapter.clear()
            regionAdapter.addAll(items.map { it.displayName })
            regionAdapter.notifyDataSetChanged()

            val selectedId = viewModel.regionId.value
            val index = items.indexOfFirst { it.id == selectedId }
            if (index >= 0) {
                binding.regionDropdown.setText(items[index].displayName, false)
            } else {
                binding.regionDropdown.text?.clear()
            }
            binding.regionLayout.isEnabled = items.isNotEmpty()
            binding.regionEmptyHint.isVisible = items.isEmpty()
            binding.submitButton.isEnabled = items.isNotEmpty() && roleItems.isNotEmpty()
        }

        viewModel.regionId.observe(viewLifecycleOwner) { id ->
            val index = regionItems.indexOfFirst { it.id == id }
            if (index >= 0) {
                binding.regionDropdown.setText(regionItems[index].displayName, false)
            }
        }

        viewModel.roleOptions.observe(viewLifecycleOwner) { options ->
            roleItems = options
            roleAdapter.clear()
            roleAdapter.addAll(options.map { resolveRoleLabel(it) })
            roleAdapter.notifyDataSetChanged()
            val hasOptions = options.isNotEmpty()
            val currentRole = viewModel.roleType.value
            val currentIndex = currentRole?.let { options.indexOf(it) } ?: -1
            when {
                currentIndex >= 0 -> binding.roleDropdown.setText(resolveRoleLabel(options[currentIndex]), false)
                !hasOptions || currentRole == null -> binding.roleDropdown.text?.clear()
            }
            binding.roleLayout.isEnabled = hasOptions
            binding.roleDropdown.isEnabled = hasOptions
            binding.submitButton.isEnabled = regionItems.isNotEmpty() && hasOptions
            binding.roleLayout.error = null
        }

        viewModel.roleType.observe(viewLifecycleOwner) { roleType ->
            val index = roleItems.indexOf(roleType)
            when {
                index >= 0 -> binding.roleDropdown.setText(resolveRoleLabel(roleItems[index]), false)
                roleType == null -> binding.roleDropdown.text?.clear()
            }
        }

        viewModel.isLoadingRegions.observe(viewLifecycleOwner) { isLoading ->
            binding.regionProgress.isVisible = isLoading
            val canInteractRegions = !isLoading && regionItems.isNotEmpty()
            val canInteractRoles = !isLoading && roleItems.isNotEmpty()
            binding.regionLayout.isEnabled = canInteractRegions
            binding.regionDropdown.isEnabled = canInteractRegions
            binding.roleLayout.isEnabled = canInteractRoles
            binding.roleDropdown.isEnabled = canInteractRoles
        }

        viewModel.submitSuccess.observe(viewLifecycleOwner) { success ->
            if (success == true) {
                Snackbar.make(binding.root, getString(R.string.user_save_success), Snackbar.LENGTH_SHORT).show()
                requireActivity().onBackPressedDispatcher.onBackPressed()
            }
        }

        viewModel.error.observe(viewLifecycleOwner) { error ->
            when (error) {
                UserFormViewModel.ErrorMessage.MissingBasicInfo -> {
                    val message = getString(R.string.user_validation_error)
                    binding.usernameLayout.error = message
                    binding.realNameLayout.error = message
                }
                UserFormViewModel.ErrorMessage.MissingRegion -> {
                    binding.regionLayout.error = getString(R.string.user_validation_region)
                }
                UserFormViewModel.ErrorMessage.MissingRole -> {
                    binding.roleLayout.error = getString(R.string.user_validation_role)
                }
                is UserFormViewModel.ErrorMessage.Custom -> {
                    Snackbar.make(binding.root, error.message, Snackbar.LENGTH_LONG).show()
                }
                null -> Unit
            }
        }
    }

    private fun resolveRoleLabel(roleType: RoleType?): String {
        return when (roleType) {
            RoleType.SUPER_ADMIN -> getString(R.string.user_role_super_admin)
            RoleType.PROVINCE_ADMIN -> getString(R.string.user_role_province_admin)
            RoleType.CITY_ADMIN -> getString(R.string.user_role_city_admin)
            RoleType.COUNTY_ADMIN -> getString(R.string.user_role_county_admin)
            RoleType.OPERATIONS_CENTER_ADMIN -> getString(R.string.user_role_center_admin)
            RoleType.STATION_ADMIN -> getString(R.string.user_role_station_admin)
            RoleType.OPERATOR -> getString(R.string.user_role_operator)
            null -> getString(R.string.user_form_role_unknown)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}



